<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never" class="card" body-style="padding:0">

        <div class="el-card-header">{{title}}</div>
        <div class="form">
          <el-form ref="form" :model="formData" label-width="100px" :rules="rules">
            <el-form-item label="学科:" prop="subject">
              <el-select v-model="formData.subject" placeholder="请选择" @change="subjectChange(formData.subject)">
                <el-option
                  v-for="item in subjectList"
                  :key="item.id"
                  :label="item.subjectName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目录:" prop="directory">
              <el-select v-model="formData.directory" placeholder="请选择">
                <el-option
                  v-for="item in directoryList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业:" prop="enterprise">
              <el-select v-model="formData.enterprise" placeholder="请选择">
                <el-option
                  v-for="item in companyList"
                  :key="item.id"
                  :label="item.company"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <!--   <el-form-item label="活动时间" required>
    <el-col :span="11">
      <el-form-item prop="date1">
        <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker>
      </el-form-item>
    </el-col>
    <el-col class="line" :span="2">-</el-col>
    <el-col :span="11">
      <el-form-item prop="date2">
        <el-time-picker placeholder="选择时间" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker>
      </el-form-item>
    </el-col>
  </el-form-item> -->
              <el-form-item label="城市:" required>
                <el-col :span="4">
                <el-form-item prop="province">
                  <el-select v-model="formData.province" placeholder="请选择" style="width:198px" @change="getNewCity">
                    <el-option
                      v-for="(item,index) in provincesList"
                      :key="index"
                      :label="item"
                      :value="item">
                    </el-option>
                  </el-select>
                 </el-form-item>
                  </el-col>
                 <el-col :span="5">
                 <el-form-item prop="city">
                  <el-select v-model="formData.city" placeholder="请选择" style="width:198px;margin-left:10px">
                    <el-option
                      v-for="(item,index) in cityList"
                      :key="index"
                      :label="item"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
                 </el-col>
              </el-form-item>
              <el-form-item label="方向:" prop="direction">
              <el-select v-model="formData.direction" placeholder="请选择" >
                <el-option
                  v-for="(item,index) in directionList"
                  :key="index"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题型:" prop="type">
              <el-radio-group v-model="formData.type">
                <el-radio label="1" checked>单选</el-radio>
                <el-radio label="2">多选</el-radio>
                <el-radio label="3">简答</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="难度:" prop="difficulty">
              <el-radio-group v-model="formData.difficulty">
                <el-radio label="1" checked>简单</el-radio>
                <el-radio label="2">一般</el-radio>
                <el-radio label="3">困难</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="题干:" prop="question">
              <!-- 富文本编辑器@blur完成校验 ref style="height:250px" -->
              <quill-editor
              v-model="formData.question"
              @blur="validateQuillEditor('question')"
               :options="editorOption" >
               </quill-editor>
            </el-form-item>
            <el-form-item label="选项:" v-if="type==='单选'">
                <el-radio-group  v-model="formData.options">
                  <el-row style="margin-top:10px;line-height:60px;height:60px"  v-for="item in formData.optionRadio" :key="item.code">
                <el-col :span="3"><el-radio :label="item.code" style="padding-top:25px">{{item.code}}:</el-radio></el-col>
                <el-col :span="10"><el-input style="width:250px" v-model="item.title"></el-input></el-col>
                <el-col :span="3"><image-upload  :selectOption='item' ref="ImageRef"></image-upload></el-col>
                  </el-row>
                  <!-- <el-row style="margin-top:10px;line-height:60px;height:60px">
                <el-col :span="3"><el-radio label="B" style="padding-top:25px">B:</el-radio></el-col>
                <el-col :span="10"><el-input style="width:250px" v-model="optionRadio[1].title"></el-input></el-col>
                <el-col :span="3"><image-upload></image-upload></el-col>
                  </el-row>
                   <el-row style="margin-top:10px;line-height:60px;height:60px">
                <el-col :span="3"><el-radio label="C" style="padding-top:25px">C:</el-radio></el-col>
                <el-col :span="10"><el-input style="width:250px" v-model="optionRadio[2].title"></el-input></el-col>
                <el-col :span="3"><image-upload></image-upload></el-col>
                  </el-row>
                  <el-row style="margin-top:10px;line-height:60px;height:60px">
                <el-col :span="3"><el-radio label="D" style="padding-top:25px">D:</el-radio></el-col>
                <el-col :span="10"><el-input style="width:250px" v-model="optionRadio[3].title"></el-input></el-col>
                <el-col :span="3"><image-upload></image-upload></el-col>
                  </el-row> -->
                </el-radio-group>
            </el-form-item>
            <el-form-item label="选项:" v-else-if="type==='多选'">
                <el-checkbox-group  v-model="formData.mutipleOptions">
                  <el-row style="margin-top:10px;line-height:60px;height:60px" v-for="item in formData.optionRadio" :key="item.code">
                <el-col :span="1"><el-checkbox :label="item.code">{{item.code}}:</el-checkbox></el-col>
                <el-col :span="4"><el-input style="width:250px" v-model="item.title"></el-input></el-col>
                <el-col :span="3"><image-upload  :selectOption='item' ref="ImageRef">
                  <!-- @imgURL="acceptImg" -->
                  </image-upload></el-col>
                  </el-row>
                  <!-- <el-row style="margin-top:10px;line-height:60px;height:60px">
                <el-col :span="1"><el-checkbox label="B">B:</el-checkbox></el-col>
                <el-col :span="4"><el-input style="width:250px"></el-input></el-col>
                <el-col :span="3"><image-upload></image-upload></el-col>
                  </el-row>
                   <el-row style="margin-top:10px;line-height:60px;height:60px">
                <el-col :span="1"><el-checkbox label="C">C:</el-checkbox></el-col>
                <el-col :span="4"><el-input style="width:250px"></el-input></el-col>
                <el-col :span="3"><image-upload></image-upload></el-col>
                  </el-row>
                  <el-row style="margin-top:10px;line-height:60px;height:60px">
                <el-col :span="1"><el-checkbox label="D">D:</el-checkbox></el-col>
                <el-col :span="4"><el-input style="width:250px"></el-input></el-col>
                <el-col :span="3"><image-upload></image-upload></el-col>
                  </el-row> -->
                </el-checkbox-group>
            </el-form-item>
            <el-form-item v-if="type!=='简答'">
                <el-button type="danger" @click="addOptions(formData.optionRadio.length)" :disabled="disabled">+增加选项与答案</el-button>
            </el-form-item>

              <el-form-item label="解析视频:">
                  <el-input v-model="formData.videoURL"></el-input>
            </el-form-item>

            <el-form-item label="答案解析:" prop="answer">
              <!-- 富文本编辑器@blur完成校验 ref style="height:250px" -->
              <quill-editor v-model="formData.answer"
              @blur="validateQuillEditor('answer')"
               :options="editorOption" >
               </quill-editor>
            </el-form-item>
            <el-form-item label="题目备注:">
              <el-input type="textarea" v-model="formData.remarks" style="width:400px"></el-input>
            </el-form-item>
            <el-form-item label="试题标签:">
                <el-select v-model="formData.tags" placeholder="请选择试题标签" multiple>
                <el-option
                  v-for="item in tagsList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
              <el-button :type="buttonType" @click="onSubmit">{{buttonTitle}}</el-button>
            </el-form-item>
          </el-form>
        </div>

      </el-card>
    </div>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import imageUpload from '../components/imageUpload.vue'
import { list } from '@/api/hmmm/subjects'
import { list as companyData } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction, questionTypes } from '@/api/hmmm/constants'
import { simple as directoryData } from '@/api/hmmm/directorys'
import { simple as tagsData } from '@/api/hmmm/tags'
import { add, detail, update } from '@/api/hmmm/questions'
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
  [{ list: 'ordered' }, { list: 'bullet' }], // 列表
  ['blockquote'], // 引用，代码块
  ['code-block', 'link', 'image']
]
export default {
  name: 'questions-new',
  data () {
    return {
      name: '郭磊',
      formData: {
        id: 0,
        subject: '', // 学科
        directory: '', // 目录
        enterprise: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        type: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: '', // 单选选项
        optionRadio: [
          {
            isRight: false,
            code: 'A',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'B',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'C',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'D',
            title: '',
            img: ''
          }
        ],
        mutipleOptions: [], // 多选选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      rules: {
        subject: [
          { required: true, message: '学科不可为空', trigger: 'change' }
        ],
        directory: [
          { required: true, message: '目录不可为空', trigger: 'change' }
        ],
        enterprise: [
          { required: true, message: '企业不可为空', trigger: 'change' }
        ],
        province: [
          { required: true, message: '城市不可为空', trigger: 'change' }
        ],
        city: [
          { required: true, message: '区域不可为空', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '方向不可为空', trigger: 'change' }
        ],
        type: [
          { required: true, message: '题型不可为空', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '难度不可为空', trigger: 'change' }
        ],
        question: [
          { required: true, message: '题干不可为空', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '答案解析不可为空', trigger: 'blur' }
        ]
      },
      imageUrl: '',
      editorOption: {
        modules: {
          toolbar: toolbarOptions
        },
        placeholder: ''
      },
      subjectList: [], // 学科列表
      companyList: [], // 公司列表
      provincesList: [], // 城市列表
      cityList: [], // 区域列表
      directionList: [], // 方向列表
      directoryList: [], // 目录
      tagsList: [], // 标签列表
      type: '单选'
    }
  },
  methods: {
    // 兜底校验确认提交
    onSubmit () {
      this.$refs.form.validate(async flag => {
        if (!flag) return
        if (this.type === '简答') this.formData.optionRadio = ''
        const form = this.formData
        const standardFormData = {
          answer: form.answer,
          subjectID: form.subject,
          catalogID: form.directory,
          enterpriseID: form.enterprise,
          province: form.province,
          city: form.city,
          direction: form.direction,
          questionType: form.type,
          difficulty: form.difficulty,
          question: form.question,
          options: form.optionRadio
          // tags: form.tags,
          // remarks: form.remarks,
          // videoURL: form.videoURL
        }
        form.tags.length !== 0 ? standardFormData.tags = form.tags : console.log(1)
        form.videoURL !== '' ? standardFormData.videoURL = form.videoURL : console.log(2)
        form.remarks !== '' ? standardFormData.remarks = form.remarks : console.log(3)
        console.log(standardFormData)
        if (this.formData.id === 0) {
          const res = await add(standardFormData)
          console.log(res)
          this.$message.success('添加成功')
        } else {
          standardFormData.id = this.formData.id
          const res = await update(standardFormData)
          console.log(res)
          this.$message.success('修改成功')
        }
        this.resetField()
        // 跳转到基础题库
        this.$router.push('/questions/list')
      })
    },
    // 增加选项与答案
    addOptions (dynamic) {
      this.formData.optionRadio.push(
        {
          code: String.fromCharCode(dynamic + 65), // asc码
          title: '',
          img: '',
          isRight: false
        }
      )
    },
    // 文件上传成功时调用的钩子函数
    handleAvatarSuccess () {

    },
    // 清空页面
    resetField () {
      this.$refs.form.resetFields()
      this.formData = {
        id: 0,
        subject: '', // 学科
        directory: '', // 目录
        enterprise: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        type: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: '', // 单选选项
        optionRadio: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ],
        mutipleOptions: [], // 多选选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      }
    },
    // 校验富文本编辑器
    validateQuillEditor (type) {
      this.$refs.form.validateField(type)
    },
    // 获取学科列表
    async getList () {
      const { data } = await list({ pagesize: 15 })
      // console.log(data.items) // 查看学科列表内容
      this.subjectList = data.items
    },
    // 获取企业列表
    async getEnterPrise () {
      const { data } = await companyData()
      // console.log(data.items) // 查看企业列表
      this.companyList = data.items
    },
    // 获取城市列表
    getProvincesList () {
      const res = provinces()
      // console.log(res)
      this.provincesList = res
    },
    // 获取区域列表
    getNewCity () {
      this.formData.city = ''
      const res = citys(this.formData.province)
      this.cityList = res
    },
    // 获取方向列表
    getDirectionList () {
      const res = direction
      // console.log(res)
      this.directionList = res
    },
    // 修改学科
    subjectChange (id) {
      this.getDirectoryList(id)
      this.getTagsList(id)
    },
    // 获取目录
    async getDirectoryList (subjectID) {
      this.formData.directory = ''
      const { data } = await directoryData({ subjectID })
      this.directoryList = data
    },
    // 获取标签
    async getTagsList (subjectID) {
      const { data } = await tagsData({ subjectID })
      this.tagsList = data
    },
    // 接收图片URL地址
    // acceptImg (val) {
    //   console.log(val)
    //   console.log(this.formData.optionRadio)
    // }
    // 修改回显数据获取
    async getEchoData () {
      const { data } = await detail({ id: Number(this.$route.query.id) })
      console.log(data)
      const form = data
      this.formData.id = form.id
      this.formData.number = form.number
      this.formData.subject = form.subjectID
      this.formData.directory = form.catalogID
      this.formData.enterprise = form.enterpriseID
      this.formData.province = form.province
      this.formData.city = form.city
      this.formData.direction = form.direction
      this.formData.type = form.questionType
      this.formData.difficulty = form.difficulty
      this.formData.question = form.question
      this.formData.optionRadio = form.options
      this.formData.videoURL = form.videoURL
      this.formData.remarks = form.remarks
      this.formData.answer = form.answer
      this.formData.tags = form.tags
      // 选项选择回显
      this.formData.optionRadio.forEach(item => {
        item.isRight = !!item.isRight
        if (item.isRight === true) {
          this.formData.options = item.code
        }
      })
      // 选项乱序问题解决
      const arr = []
      const arr2 = []
      form.options.forEach((item, index) => {
        arr.push(String.fromCharCode(index + 65))
      })
      arr.forEach(item => {
        form.options.forEach(itemtt => {
          if (item === itemtt.code) {
            arr2.push(itemtt)
          }
        })
      })
      this.formData.optionRadio = arr2
      // 回显图片
      this.formData.optionRadio.forEach((item, index) => {
        if (item.img) {
          this.$refs.ImageRef[index].fileList.push({ url: item.img })
        }
      })
    }
  },
  watch: {
    'formData.type': {
      deep: true,
      handler () {
        const res = questionTypes.filter(item => item.value === this.formData.type)
        this.type = res[0].label
      }
    },
    'formData.options': {
      deep: true,
      handler () {
        const a = this.formData.options
        if (a === 'A') {
          this.formData.optionRadio.forEach(item => {
            item.isRight = false
          })
          this.formData.optionRadio[0].isRight = true
        } else if (a === 'B') {
          this.formData.optionRadio.forEach(item => {
            item.isRight = false
          })
          this.formData.optionRadio[1].isRight = true
        } else if (a === 'C') {
          this.formData.optionRadio.forEach(item => {
            item.isRight = false
          })
          this.formData.optionRadio[2].isRight = true
        } else if (a === 'D') {
          this.formData.optionRadio.forEach(item => {
            item.isRight = false
          })
          this.formData.optionRadio[3].isRight = true
        }
      }
    },
    'formData.mutipleOptions': {
      deep: true,
      handler () {
        const a = this.formData.mutipleOptions
        this.formData.optionRadio.forEach(item => {
          a.forEach(item2 => {
            if (item.code === item2) {
              item.isRight = true
            }
          })
        }
        )
      }
    }
  },
  components: {
    quillEditor,
    imageUpload
  },
  computed: {
    title () {
      return this.formData.id === 0 ? '试题录入' : '试题修改'
    },
    buttonType () {
      return this.formData.id === 0 ? 'primary' : 'success'
    },
    disabled () {
      return this.type !== '多选'
    },
    buttonTitle () {
      return this.formData.id === 0 ? '确认提交' : '确认修改'
    }
  },
  created () {
    // this.$route.query
    this.getList()
    this.getEnterPrise()
    this.getProvincesList()
    this.getDirectionList()
    if (this.$route.query.id) {
      this.getEchoData()
    }
  }
}
</script>

<style scoped lang="scss">
.card{
    .form{
      padding: 20px;
      .el-select{
        width: 400px;
      }
      .el-input{
        width: 400px;
      }
    }
  }
    .el-card-header{
    box-sizing: border-box;
    padding: 18px 20px;
    border-bottom: 1px solid #ccc;
    }
</style>
